<template>
  <div class="order-list">
    <MyPanel title="我的订单" subTitle="查看和管理您的订单">
      <div v-if="orders.length > 0" class="orders-content">
        <div class="order-item" v-for="order in orders" :key="order.orderId">
          <div class="order-header">
            <div class="order-no">订单号：{{ order.orderNo }}</div>
            <div class="order-status" :class="getStatusClass(order.status)">
              {{ getStatusText(order.status) }}
            </div>
          </div>
          
          <div class="order-body">
            <div class="order-items">
              <div class="order-item-product" v-for="item in order.orderItems" :key="item.orderItemId">
                <div class="product-image">
                  <img :src="item.productImageUrl || item.product?.imageUrl || defaultImage" :alt="item.productName" />
                </div>
                <div class="product-info">
                  <div class="product-name">{{ item.productName }}</div>
                  <div class="product-price">¥{{ item.price }}</div>
                </div>
                <div class="product-quantity">x {{ item.quantity }}</div>
                <div class="product-total">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              </div>
            </div>
            
            <div class="order-summary">
              <div class="summary-item">
                <span>总金额：</span>
                <span class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</span>
              </div>
              <div class="summary-item">
                <span>下单时间：</span>
                <span>{{ formatDate(order.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-actions">
              <button 
                v-if="order.status === 1" 
                class="action-btn pay-btn"
                @click="handlePayOrder(order)"
              >
                立即支付
              </button>
              <button 
                v-if="order.status === 3" 
                class="action-btn confirm-btn"
                @click="handleConfirmReceipt(order)"
              >
                确认收货
              </button>
              <button 
                v-if="order.status === 4" 
                class="action-btn review-btn"
                @click="reviewOrder(order)"
              >
                评价
              </button>
              <button 
                class="action-btn detail-btn"
                @click="viewOrderDetail(order)"
              >
                订单详情
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空订单提示 -->
      <div v-else class="empty-orders">
        <div class="empty-icon">
          <i class="iconfont icon-order"></i>
        </div>
        <p>您还没有订单</p>
        <router-link to="/" class="go-shopping-btn">
          去逛逛
        </router-link>
      </div>
    </MyPanel>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import MyPanel from "@/components/MyPanel.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { getUserOrders, payOrder, confirmReceipt } from "@/api";

export default {
  components: {
    MyPanel
  },
  setup() {
    const router = useRouter();
    const orders = ref([]);
    const defaultImage = ref(""); // 默认图片地址
    
    // 获取订单列表
    const fetchOrders = async () => {
      try {
        // 调用获取订单列表的API
        const res = await getUserOrders();
        if (res.code === 200) {
          orders.value = res.data;
        } else {
          ElMessage.error(res.message || "获取订单列表失败");
        }
      } catch (error) {
        console.error("获取订单列表失败:", error);
        ElMessage.error("获取订单列表失败");
      }
    };
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        1: "待支付",
        2: "已支付",
        3: "已发货",
        4: "已完成",
        5: "已取消"
      };
      return statusMap[status] || "未知状态";
    };
    
    // 获取状态样式类
    const getStatusClass = (status) => {
      const classMap = {
        1: "status-pending",
        2: "status-paid",
        3: "status-shipped",
        4: "status-completed",
        5: "status-cancelled"
      };
      return classMap[status] || "";
    };
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return "";
      return new Date(date).toLocaleString('zh-CN');
    };
    
    // 立即支付
    const handlePayOrder = async (order) => {
      try {
        const res = await payOrder(order.orderId);
        if (res.code === 200 && res.data) {
          ElMessage.success("支付成功");
          // 更新订单状态
          order.status = 2;
        } else {
          ElMessage.error(res.message || "支付失败");
        }
      } catch (error) {
        console.error("支付失败:", error);
        ElMessage.error("支付失败，请稍后重试");
      }
    };
    
    // 确认收货
    const handleConfirmReceipt = (order) => {
      ElMessageBox.confirm("确认收货后将无法撤销，是否确认收货？", "确认收货", {
        type: "warning"
      }).then(async () => {
        try {
          // 调用确认收货的API
          const res = await confirmReceipt(order.orderId);
          if (res.code === 200 && res.data) {
            ElMessage.success("确认收货成功");
            // 更新订单状态
            order.status = 4;
            // 重新获取订单列表以更新状态
            await fetchOrders();
          } else {
            ElMessage.error(res.message || "确认收货失败");
          }
        } catch (error) {
          console.error("确认收货失败:", error);
          ElMessage.error("确认收货失败，请稍后重试");
        }
      }).catch(() => {
        // 用户取消操作
      });
    };
    
    // 评价订单
    const reviewOrder = (order) => {
      ElMessage.info(`跳转到评价页面，订单号：${order.orderNo}`);
      // 这里应该跳转到评价页面
    };
    
    // 查看订单详情
    const viewOrderDetail = (order) => {
      ElMessage.info(`查看订单详情，订单号：${order.orderNo}`);
      // 这里应该跳转到订单详情页面
    };
    
    onMounted(() => {
      fetchOrders();
    });
    
    return {
      orders,
      defaultImage,
      getStatusText,
      getStatusClass,
      formatDate,
      handlePayOrder,
      handleConfirmReceipt,
      reviewOrder,
      viewOrderDetail
    };
  }
};
</script>

<style lang="less" scoped>
@import "@/assets/styles/variables.less";

.order-list {
  .orders-content {
    .order-item {
      border: 1px solid #eee;
      border-radius: 4px;
      margin-bottom: 20px;
      overflow: hidden;
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        background-color: #f8f8f8;
        border-bottom: 1px solid #eee;
        
        .order-no {
          font-weight: bold;
        }
        
        .order-status {
          padding: 4px 10px;
          border-radius: 2px;
          font-size: 14px;
          
          &.status-pending {
            background-color: #fff3cd;
            color: #856404;
          }
          
          &.status-paid {
            background-color: #cce5ff;
            color: #004085;
          }
          
          &.status-shipped {
            background-color: #d1ecf1;
            color: #0c5460;
          }
          
          &.status-completed {
            background-color: #d4edda;
            color: #155724;
          }
          
          &.status-cancelled {
            background-color: #f8d7da;
            color: #721c24;
          }
        }
      }
      
      .order-body {
        padding: 20px;
        
        .order-items {
          .order-item-product {
            display: flex;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #f5f5f5;
            
            .product-image {
              width: 80px;
              height: 80px;
              margin-right: 15px;
              
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            
            .product-info {
              flex: 1;
              
              .product-name {
                font-size: 16px;
                margin-bottom: 5px;
              }
              
              .product-price {
                font-size: 16px;
                color: @priceColor;
                font-weight: bold;
              }
            }
            
            .product-quantity {
              width: 60px;
              text-align: center;
            }
            
            .product-total {
              width: 100px;
              text-align: right;
              font-weight: bold;
              color: @priceColor;
            }
          }
        }
        
        .order-summary {
          display: flex;
          justify-content: flex-end;
          margin-top: 15px;
          
          .summary-item {
            margin-left: 20px;
            
            .total-amount {
              font-size: 18px;
              color: @priceColor;
              font-weight: bold;
            }
          }
        }
      }
      
      .order-footer {
        padding: 15px 20px;
        background-color: #f8f8f8;
        border-top: 1px solid #eee;
        
        .order-actions {
          display: flex;
          justify-content: flex-end;
          
          .action-btn {
            margin-left: 10px;
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
            cursor: pointer;
            
            &:hover {
              background-color: #f5f5f5;
            }
            
            &.pay-btn {
              background-color: @xtxColor;
              color: white;
              border-color: @xtxColor;
              
              &:hover {
                background-color: #b8884d;
              }
            }
            
            &.confirm-btn {
              background-color: #28a745;
              color: white;
              border-color: #28a745;
              
              &:hover {
                background-color: #218838;
              }
            }
          }
        }
      }
    }
  }
  
  .empty-orders {
    text-align: center;
    padding: 50px 0;
    
    .empty-icon {
      font-size: 80px;
      color: #ccc;
      margin-bottom: 20px;
    }
    
    p {
      font-size: 18px;
      color: #666;
      margin-bottom: 30px;
    }
    
    .go-shopping-btn {
      display: inline-block;
      padding: 10px 30px;
      background-color: @xtxColor;
      color: white;
      border-radius: 4px;
      text-decoration: none;
      
      &:hover {
        background-color: #b8884d;
      }
    }
  }
}
</style>